package com.jasonchoi.security.service;

import cn.hutool.core.util.StrUtil;
import com.jasonchoi.security.entity.User;
import com.jasonchoi.security.repository.UserRepository;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserService implements UserDetailsService {

	@Resource
	private UserRepository repository;

	@Override
	public UserDetails loadUserByUsername(String username) {
		User user = repository.findByUsername(username);
		if (Objects.isNull(user)) {
			return null;
		}

		//用户权限
		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		if (StrUtil.isNotBlank(user.getRoles())) {
			String[] roles = user.getRoles().split(",");
			authorities = Arrays.asList(roles).stream().filter(StrUtil::isNotBlank)
								.map(role -> new SimpleGrantedAuthority(role.trim()))
								.collect(Collectors.toList());
		}
		return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
	}

	public User userInfo() {
		System.out.println("userInfo....");
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		UserDetails userDetail = (UserDetails) authentication.getPrincipal();
		return new User().setUsername(userDetail.getUsername())
						 .setPassword(userDetail.getPassword())
						 .setRoles(StrUtil.join(",", userDetail.getAuthorities()));
	}

}
